#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#include <process.h>
#define BUFF_LENGTH 1024
#define USERNAME_LENGTH 32
unsigned __stdcall ReceiveMessages(void *arg){
SOCKET sock = *(SOCKET *)arg;
char buffer[BUFF_LENGTH];
int recv_len;
while ((recv_len = recv(sock, buffer, BUFF_LENGTH - 1, 0)) > 0){
    buffer[recv_len] = '\0';
    printf("%s", buffer); 
}

return 0;
}
int main(){
    WSADATA wsa_data;
if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0){
        printf("WSAStartup failed\n");
        return 1;
}
    SOCKET client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (client_socket == INVALID_SOCKET){
        printf("Socket creation failed\n");
        WSACleanup();
        return 1;
	}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET; 
server_addr.sin_port = htons(8080);
char server_ip[16];
printf("输入你的用户名：");
scanf("%s", server_ip);
getchar();
server_addr.sin_addr.s_addr = inet_addr(server_ip);
if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR){
    printf("Connection failed\n");
    closesocket(client_socket);
    WSACleanup();
    return 1;
}
printf("Connected to server\n");
char buffer[BUFF_LENGTH];
int recv_len = recv(client_socket, buffer, BUFF_LENGTH - 1, 0);
buffer[recv_len] = '\0';
printf("%s", buffer);
char username[USERNAME_LENGTH];
fgets(username, USERNAME_LENGTH, stdin);
username[strcspn(username, "\n")] = 0;
send(client_socket, username, strlen(username), 0);
_beginthreadex(NULL, 0, ReceiveMessages, &client_socket, 0, NULL);
char message[BUFF_LENGTH];
while (1){
    fgets(message, BUFF_LENGTH, stdin);
    if (strcmp(message, "quit\n") == 0){
            break;
    }
    if (send(client_socket, message, strlen(message), 0) == SOCKET_ERROR){
            printf("Send failed\n");
            break;
    }
}
closesocket(client_socket);
WSACleanup(); 
}